import store from "@/store/index"
import { permStore } from "@/store/module/perms"
import type { Router, RouteRecordRaw } from "vue-router"

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    // 如果路由对象meta中requireAuth为真，并且校验token没失效。则可以跳转至页面路由。
    // const isAuth = isAuthenticated()
    // console.log(isAuth)

    const whiteList = ["/login"]

    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log("store.state.token", store.state.token)
      console.log(router.getRoutes())
      console.log(router.hasRoute("/sys/menu"))

      if (store.state.token) {
        //
        console.log("permStore.getIsDynamicAddedRouteState", permStore.getIsDynamicAddedRouteState)
        if (permStore.getIsDynamicAddedRouteState) {
          next()
        } else {
          const routesComp = await permStore.generateMenusRoutes()
          routesComp.forEach(route => {
            router.addRoute(route as RouteRecordRaw)
          })
          const redirectPath = (from.query.redirect || to.path) as string
          const redirect = decodeURIComponent(redirectPath)
          console.log("redirectredirectredirectredirect", redirect)
          const nextData = to.path === redirect ? { path: redirect } : { ...to, replace: true }
          permStore.commitDynamicAddedRouteState(true)
          // console.log(routesComp, ...to.path)
          // 研究一下什么时候需要 next({...to, replace:true})
          next(nextData)
        }
      } else {
        next({ name: "login" })
      }
    }
  })
}
